import * as THREE from 'three'; // 确保导入 THREE.js
import test from './test';
import sceneMrg from '../sceneMrg';
import { requestJSON } from "@/js/url";
import cabinetModel from '@/cabinetModel/index';

class DeviceMrg {
    init() {}
    equipment(id) {
      return `/equipment/${id}`;
    }
    async start(param) {
        this.deviceSlotHeight = param.deviceSlotHeight;

        // 创建一个父节点
        const parentGroup = new THREE.Group();
        sceneMrg.scene.add(parentGroup); // 将父节点添加到场景中
		
		let url = window.location.href
		const parsedUrl = new URL(url);
        // 使用 URLSearchParams 解析查询参数
        const params = new URLSearchParams(parsedUrl.search);
        
        // 创建一个空对象
        const paramsObject = {};
        
        // 遍历所有参数，并将其添加到对象中
        params.forEach((value, key) => {
          paramsObject[key] = value;
        });
		let list = (await requestJSON({ url: this.equipment(paramsObject.id) })).data;
		console.log("设备参数",list);
        let dataer = { 
				"type_name": list.equipcat_name,
				"is_master": list.is_master,
				"type_id": list.equipcat_id,
				"ip": list.ip,
				"back_view": list.back_view_url,
				"model_id": list.equipmod_id,
				"view":list.front_view_url,
				"model_name": list.equipmod_name,
				"serial": list.serial,
				"pos":list.position,
				"parent_id":list.parent_id,
				"name": list.name,
				"id": list.id,
				"glb": list.front_view_url,
				"fbx": list.owner,
				"brand": list.equipmod_name,
				"height": list.u_height,
				"status":list.status
				}
        // 输出结果
        // 创建柜子模型并添加到父节点中
        const cabinet = new cabinetModel({
            data:dataer,   // test[4],
            parent: parentGroup, // 将父节点作为父对象
            deviceSlotHeight: this.deviceSlotHeight
        });

        // 创建立方体并添加到父节点中
        const boxSize = 0.5; // 立方体的大小
        //const box = this.createBox(boxSize);
       // parentGroup.add(box); // 将立方体添加到父节点
        const scaleFactor = 2.5; // 放大因子
        parentGroup.scale.set(scaleFactor, scaleFactor, scaleFactor); // 缩放父节点
        // 计算并设置父节点的位置以居中
        this.centerParentGroup(parentGroup);
    }

    createBox(size) {
        // 创建一个立方体几何体
        const geometry = new THREE.BoxGeometry(size, size, size);
        
        // 创建一个材质
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 绿色
        
        // 创建一个网格对象
        const box = new THREE.Mesh(geometry, material);
        
        // 可选：设置立方体的位置
        box.position.set(0, size / 2, 0); // 将立方体抬高一半，以便它在地面上

        return box; // 返回创建的立方体
    }

    centerParentGroup(parentGroup) {
        // 计算包围盒
        const box = new THREE.Box3().setFromObject(parentGroup);
        const center = new THREE.Vector3();
        box.getCenter(center);

        // 将父节点移动到中心
        const offsetY = 1.2; // 向上偏移的量
        parentGroup.position.copy(center.negate()).add(new THREE.Vector3(0, offsetY, 0));
    }
}

export default new DeviceMrg();
